package com.example.bookmanage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bookmanage.domain.book.Book;
import com.example.bookmanage.domain.borrow.vo.BorrowVO;
import com.example.bookmanage.domain.reader.Reader;
import com.example.bookmanage.domain.reader.dto.ReaderDTO;
import com.example.bookmanage.domain.reader.dto.ReaderEditDTO;
import com.example.bookmanage.domain.reader.dto.ReaderQueDTO;
import com.example.bookmanage.domain.reader.dto.ReaderUpStatusDTO;
import com.example.bookmanage.domain.reader.vo.ReaderVO;
import com.example.bookmanage.mapper.BookMapper;
import com.example.bookmanage.mapper.BorrowMapper;
import com.example.bookmanage.service.ReaderService;
import com.example.bookmanage.mapper.ReaderMapper;
import com.example.bookmanage.utils.BCryptUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lyk19
 * @description 针对表【reader_db】的数据库操作Service实现
 * @createDate 2025-02-01 20:59:02
 */
@Service
public class ReaderServiceImpl extends ServiceImpl<ReaderMapper, Reader>
        implements ReaderService {

    @Autowired
    private ReaderMapper readerMapper;

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private BookMapper bookMapper;

    /**
     * 读者列表
     *
     * @param readerQueDTO
     * @return
     */
    public List<ReaderVO> list(ReaderQueDTO readerQueDTO) {
        PageHelper.startPage(readerQueDTO.getPageNum(), readerQueDTO.getPageSize());
        return readerMapper.selectReaderList(readerQueDTO);
    }

    /**
     * 添加读者
     *
     * @param readerDTO
     * @return
     */
    public int save(ReaderDTO readerDTO) {
        Reader reader = new Reader();

        BeanUtil.copyProperties(readerDTO, reader);

        // 生成唯一的6位数字
        Long uniqueNumber = generateUniqueSixDigitNumber();
        reader.setCardId(uniqueNumber);
        reader.setNickname(readerDTO.getUsername());
        reader.setPassword(BCryptUtils.encryptPassword("123456"));
        reader.setStatus(0);

        return readerMapper.insert(reader);
    }

    /**
     * 修改读者信息
     *
     * @param readerEditDTO
     * @return
     */
    public int update(ReaderEditDTO readerEditDTO) {
        Reader reader = new Reader();

        BeanUtil.copyProperties(readerEditDTO, reader);

        return readerMapper.updateByCardId(reader);
    }

    /**
     * 修改读者状态
     *
     * @param readerUpStatusDTO
     * @return
     */
    public int updateStatus(ReaderUpStatusDTO readerUpStatusDTO) {
        UpdateWrapper<Reader> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("reader_id", readerUpStatusDTO.getReaderId())
                .set("status", readerUpStatusDTO.getStatus());
        return readerMapper.update(null, updateWrapper);
    }

    /**
     * 查询读者借阅记录
     *
     * @param readerId
     * @return
     */
    public List<BorrowVO> getBorrowRecords(Long readerId) {
        List<BorrowVO> borrowRecords = borrowMapper.getBorrowRecords(readerId);

        if(CollectionUtil.isEmpty(borrowRecords)){
            return null;
        }

        List<Long> bookIds = borrowRecords.stream()
                .map(BorrowVO::getBookId)
                .toList();
        bookMapper.selectBatchIds(bookIds).forEach(book -> {
            borrowRecords.forEach(borrowVO -> {
                if (book.getBookId().equals(borrowVO.getBookId())) {
                    borrowVO.setBookName(book.getBookName());
                }
            });
        });

        return borrowRecords;
    }

    /**
     * 生成唯一的6位数字
     *
     * @return
     */
    private Long generateUniqueSixDigitNumber() {
        // 获取当前的最后生成的数字
        Long lastGeneratedNumber = readerMapper.getLastGeneratedNumber();

        // 生成新的6位数字
        Long newNumber = (lastGeneratedNumber % 999999) + 1;

        // 更新最后生成的数字
        readerMapper.updateLastGeneratedNumber(newNumber);

        return newNumber;
    }
}
